import cv2

red = (0, 0, 255)


# ==============================
# 多边形逼近
# ==============================
def test1():
    #
    src = cv2.imread('graph.png')

    # 转换颜色空间
    img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    # 查找轮廓
    contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    # 绘制轮廓
    my_img = cv2.drawContours(src, contours, 0, red, 5)
    cv2.imshow('img_copy', my_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    # 使用多边形逼近，近似模拟多边形的轮廓
    approx = cv2.approxPolyDP(contours[0], 6, closed=True)
    # approx 本质是一个类型的轮廓
    # 画出多边形逼近的轮廓
    cv2.drawContours(my_img, [approx], 0, (0, 255, 0), 2)

    cv2.imshow('img_11copy', my_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
